
package com.qualitair44.data.utils;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Properties;
import java.util.TimeZone;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.qualitair44.data.Mesure;

public class Retriever {
	private static Calendar getNearestDay(Calendar from, int diff)
	{
		int dayCurrent = from.getTime().getDay();
		Calendar res = (Calendar) from.clone();
		res.add(Calendar.YEAR, diff);
		int dayBefore = res.getTime().getDay();
		res.add(Calendar.DATE,dayBefore-dayCurrent);
		return res;
	}
	
	public static ArrayList<Mesure> getATMOS(Date currentD, String IdCity) {
		String url = "http://www.airpl.org/indices?agglo="+IdCity+
				"&j="+currentD.getDate()+
				"&m="+(currentD.getMonth()+1)+
				"&a="+(1900+currentD.getYear())+
				"&week=Ok&p=";
		
		ArrayList<Mesure> res  = new ArrayList<Mesure> ();
		Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
		} catch (IOException e) {
			e.printStackTrace();
		}

		Elements elements = doc.select("table[class=table_indice]>tbody>tr"); // a with href
		Iterator<Element> i = elements.iterator();
		if(i.hasNext()){
			i.next();
		}
		
		
		while (i.hasNext()) {
			
			Element elem = (Element) i.next();
			Elements td = elem.select("td");
			if(td.get(5).html().trim().length() != 0){
				Mesure m = new Mesure(td);
				res.add(m);
			}
		}
		return res;
	}
	
	public static Mesure getAtmo(Date currentD, String IdCity)
	{
		String url = "http://www.airpl.org/indices?agglo="+IdCity+
				"&j="+currentD.getDate()+
				"&m="+(currentD.getMonth()+1)+
				"&a="+(1900+currentD.getYear())+
				"&week=Ok&p=";
		
		
		Document doc = null;
		try {
			doc = Jsoup.connect(url).get();
		} catch (IOException e) {
			e.printStackTrace();
		}

		Elements elements = doc.select("table[class=table_indice]>tbody>tr"); // a with href
		
		Element elem = elements.get(7);
		Elements td = elem.select("td");
		
		
		Mesure m = new Mesure(td);
		return m;
	}
	
	public static Mesure getNow(String idCity)
	{
		return getAtmo(Calendar.getInstance().getTime(),idCity);
	}
}
